import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../models/category_model.dart';
import '../../services/api_service.dart';
import '../../widgets/simple_rich_text_editor.dart';
import '../../utils/logger.dart';
import '../../utils/compress_utils.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'publish_article_page.dart';

/// 发表动态页面 - 重构版
/// 根据动态类型显示不同的发布表单
class PublishPostPageV4 extends StatefulWidget {
  const PublishPostPageV4({super.key});

  @override
  State<PublishPostPageV4> createState() => _PublishPostPageV4State();
}

class _PublishPostPageV4State extends State<PublishPostPageV4> {
  // 基础字段
  final _titleController = TextEditingController();
  String _selectedPostType = 'article'; // 默认选择文章类型
  List<Category> _categories = [];
  Category? _selectedCategory;
  bool _isPublishing = false;
  bool _isLoading = false;
  
  // API服务
  final _apiService = ApiService();

  // 动态类型配置（已移除图文类型，文章支持富文本图文并茂）
  final List<Map<String, dynamic>> _postTypes = [
    {
      'value': 'article',
      'name': '文章',
      'icon': Icons.article,
      'description': '支持富文本编辑，图文并茂',
      'color': Colors.blue
    },
    {
      'value': 'video',
      'name': '视频',
      'icon': Icons.videocam,
      'description': '发布视频内容',
      'color': Colors.purple
    },
    {
      'value': 'service',
      'name': '商品',
      'icon': Icons.shopping_bag,
      'description': '发布商品或服务',
      'color': Colors.orange
    },
  ];

  // 图文类型字段
  String? _coverImageUrl;
  final _contentController = TextEditingController();
  List<String> _imageUrls = [];

  // 文章类型字段
  final _articleContentController = SimpleRichTextEditorController();

  // 视频类型字段
  String? _videoUrl;
  String? _videoCoverUrl;
  final _videoDescriptionController = TextEditingController();

  // 商品类型字段
  final _productNameController = TextEditingController();
  final _productPriceController = TextEditingController();
  final _productDescriptionController = TextEditingController();
  List<String> _productImages = [];

  // 原创标识
  bool _isOriginal = true;

  @override
  void initState() {
    super.initState();
    _loadCategories();
  }

  /// 跳转到文章编辑页面
  Future<void> _navigateToArticlePage() async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PublishArticlePage(),
      ),
    );
    
    // 如果文章发布成功，返回上一页
    if (result == true && mounted) {
      Navigator.of(context).pop(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('发表动态'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 1,
        actions: [
          TextButton(
            onPressed: _isPublishing ? null : _publishPost,
            child: Text(
              '发布',
              style: TextStyle(
                color: _isPublishing ? Colors.grey : Colors.blue,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            _buildPostTypeSelector(),
            const SizedBox(height: 16),
            _buildTitleSection(),
            const SizedBox(height: 16),
            _buildCategorySection(),
            const SizedBox(height: 16),
            _buildOriginalSection(),
            const SizedBox(height: 16),
            _buildContentSection(),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  /// 构建动态类型选择器
  Widget _buildPostTypeSelector() {
    return _buildCard(
      icon: Icons.category,
      title: '选择动态类型',
      child: Column(
        children: _postTypes.map((type) {
          final isSelected = _selectedPostType == type['value'];
          return Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: GestureDetector(
              onTap: () {
                if (type['value'] == 'article') {
                  // 跳转到专门的文章编辑页面
                  _navigateToArticlePage();
                } else {
                  setState(() => _selectedPostType = type['value']);
                }
              },
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: isSelected
                      ? (type['color'] as Color).withOpacity(0.1)
                      : Colors.grey[50],
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: isSelected ? type['color'] as Color : Colors.grey[300]!,
                    width: isSelected ? 2 : 1,
                  ),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: (type['color'] as Color).withOpacity(0.15),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Icon(
                        type['icon'],
                        size: 22,
                        color: type['color'] as Color,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            type['name'],
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.w600,
                              color: isSelected
                                  ? type['color'] as Color
                                  : Colors.grey[800],
                            ),
                          ),
                          if (type['description'] != null) ...[
                            const SizedBox(height: 2),
                            Text(
                              type['description'],
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                    if (isSelected)
                      Icon(
                        Icons.check_circle,
                        color: type['color'] as Color,
                        size: 22,
                      ),
                  ],
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建标题输入
  Widget _buildTitleSection() {
    return _buildCard(
      icon: Icons.title,
      title: '标题',
      child: TextField(
        controller: _titleController,
        decoration: const InputDecoration(
          hintText: '请输入动态标题（2-50个字符）',
          border: OutlineInputBorder(),
        ),
        maxLength: 50,
      ),
    );
  }

  /// 构建分类选择
  Widget _buildCategorySection() {
    return _buildCard(
      icon: Icons.folder,
      title: '选择分类',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (_selectedCategory != null) ...[
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: _selectedCategory!.color != null 
                    ? Color(int.parse(
                        _selectedCategory!.color!.replaceAll('#', '0xFF')))
                    : Colors.blue,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (_selectedCategory!.icon != null) ...[
                    Icon(
                      Icons.folder,
                      color: Colors.white,
                      size: 16,
                    ),
                    const SizedBox(width: 6),
                  ],
                  Text(
                    _selectedCategory!.name,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(width: 6),
                  GestureDetector(
                    onTap: () => setState(() => _selectedCategory = null),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 16,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
          ],
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _categories.map((category) {
              final isSelected = _selectedCategory?.id == category.id;
              final categoryColor = category.color != null 
                  ? Color(int.parse(category.color!.replaceAll('#', '0xFF')))
                  : Colors.grey;
              
              return GestureDetector(
                onTap: () => setState(() => _selectedCategory = category),
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: isSelected 
                        ? categoryColor.withOpacity(0.2)
                        : Colors.grey[100],
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(
                      color: isSelected ? categoryColor : Colors.grey[300]!,
                      width: isSelected ? 2 : 1,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (category.icon != null) ...[
                        Icon(
                          Icons.folder,
                          color: isSelected ? categoryColor : Colors.grey[600],
                          size: 16,
                        ),
                        const SizedBox(width: 6),
                      ],
                      Text(
                        category.name,
                        style: TextStyle(
                          color: isSelected ? categoryColor : Colors.grey[700],
                          fontSize: 14,
                          fontWeight:
                              isSelected ? FontWeight.w600 : FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 构建原创标识切换
  Widget _buildOriginalSection() {
    return _buildCard(
      icon: Icons.copyright,
      title: '原创标识',
      child: Row(
        children: [
          Switch(
            value: _isOriginal,
            onChanged: (value) => setState(() => _isOriginal = value),
          ),
          const SizedBox(width: 12),
          Text(
            _isOriginal ? '原创内容' : '转载内容',
            style: TextStyle(
              fontSize: 16,
              color: _isOriginal ? Colors.green : Colors.orange,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建内容区域（根据类型动态显示）
  Widget _buildContentSection() {
    switch (_selectedPostType) {
      case 'article':
        return _buildArticleContentSection();
      case 'video':
        return _buildVideoContentSection();
      case 'service':
        return _buildServiceContentSection();
      default:
        return _buildArticleContentSection(); // 默认显示文章编辑
    }
  }

  /// 图文内容区域
  Widget _buildTextContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.image,
          title: '封面图片',
          child: GestureDetector(
            onTap: _selectCoverImage,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _coverImageUrl != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          Image.network(_coverImageUrl!,
                              fit: BoxFit.cover,
                              width: double.infinity,
                              height: double.infinity),
                          Positioned(
                            top: 8,
                            right: 8,
                            child: GestureDetector(
                              onTap: () =>
                                  setState(() => _coverImageUrl = null),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(
                                    color: Colors.black54,
                                    shape: BoxShape.circle),
                                child: const Icon(Icons.close,
                                    color: Colors.white, size: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.add_photo_alternate,
                            size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择封面图',
                            style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '文字描述',
          child: TextField(
            controller: _contentController,
            decoration: const InputDecoration(
              hintText: '分享你的想法...',
              border: OutlineInputBorder(),
            ),
            maxLines: 5,
            maxLength: 500,
          ),
        ),
      ],
    );
  }

  /// 文章内容区域
  Widget _buildArticleContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.image,
          title: '文章封面',
          child: GestureDetector(
            onTap: _selectCoverImage,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _coverImageUrl != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          Image.network(_coverImageUrl!,
                              fit: BoxFit.cover,
                              width: double.infinity,
                              height: double.infinity),
                          Positioned(
                            top: 8,
                            right: 8,
                            child: GestureDetector(
                              onTap: () =>
                                  setState(() => _coverImageUrl = null),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(
                                    color: Colors.black54,
                                    shape: BoxShape.circle),
                                child: const Icon(Icons.close,
                                    color: Colors.white, size: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.add_photo_alternate,
                            size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择文章封面',
                            style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '文章内容',
          child: SimpleRichTextEditor(
            controller: _articleContentController,
            hintText: '编写你的文章，支持图文混排...',
            minHeight: 200,
          ),
        ),
      ],
    );
  }

  /// 视频内容区域
  /// 布局顺序：1.视频描述 2.视频封面 3.视频文件（符合验证逻辑）
  Widget _buildVideoContentSection() {
    return Column(
      children: [
        // 1. 视频描述 - 放在最上面，必须先填写
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.edit, color: Colors.purple[600], size: 20),
                      const SizedBox(width: 8),
                      Text('视频描述',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.red.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text(
                          '必填',
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _videoDescriptionController,
                    decoration: InputDecoration(
                      hintText: '描述你的视频内容、亮点、创作灵感等...',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide:
                            BorderSide(color: Colors.blue[400]!, width: 2),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 16),
                    ),
                    maxLines: 3,
                    maxLength: 200,
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),

        // 2. 视频封面 - 必须先上传封面
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.photo, color: Colors.blue[600], size: 20),
                      const SizedBox(width: 8),
                      Text('视频封面',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.red.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text(
                          '必填',
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  GestureDetector(
                    onTap: _selectVideoCover,
                    child: Container(
                      width: double.infinity,
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(8),
                        border:
                            Border.all(color: Colors.grey[300]!, width: 1.5),
                      ),
                      child: _videoCoverUrl != null
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Stack(
                                children: [
                                  Image.network(_videoCoverUrl!,
                                      fit: BoxFit.cover,
                                      width: double.infinity,
                                      height: double.infinity),
                                  const Center(
                                    child: Icon(Icons.play_circle_filled,
                                        size: 48, color: Colors.white),
                                  ),
                                  Positioned(
                                    top: 8,
                                    right: 8,
                                    child: GestureDetector(
                                      onTap: () =>
                                          setState(() => _videoCoverUrl = null),
                                      child: Container(
                                        padding: const EdgeInsets.all(4),
                                        decoration: const BoxDecoration(
                                            color: Colors.black54,
                                            shape: BoxShape.circle),
                                        child: const Icon(Icons.close,
                                            color: Colors.white, size: 16),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.add_photo_alternate,
                                    size: 48, color: Colors.grey[400]),
                                const SizedBox(height: 12),
                                Text('点击选择视频封面',
                                    style: TextStyle(
                                        color: Colors.grey[600], fontSize: 14)),
                                const SizedBox(height: 4),
                                Text('建议尺寸：16:9',
                                    style: TextStyle(
                                        color: Colors.grey[500], fontSize: 12)),
                              ],
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        // 3. 视频文件上传 - 放在最后，需要先完成描述和封面
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.videocam, color: Colors.red[600], size: 20),
                      const SizedBox(width: 8),
                      Text('视频文件',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.orange.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          '最后上传',
                          style: TextStyle(
                            color: Colors.orange[700],
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                  // 提示信息：需要先完成描述和封面
                  if (_videoDescriptionController.text.trim().isEmpty ||
                      _videoCoverUrl == null)
                    Container(
                      margin: const EdgeInsets.only(bottom: 12),
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.orange.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(6),
                        border:
                            Border.all(color: Colors.orange.withOpacity(0.3)),
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.info_outline,
                              size: 16, color: Colors.orange[700]),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Text(
                              '请先完成视频描述和封面上传，再上传视频文件',
                              style: TextStyle(
                                color: Colors.orange[700],
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ],
                      ),
                  ),
                  const SizedBox(height: 12),
                  GestureDetector(
                    onTap: _selectVideo,
                    child: Container(
                      width: double.infinity,
                      height: 120,
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(8),
                        border:
                            Border.all(color: Colors.grey[300]!, width: 1.5),
                      ),
                      child: _videoUrl != null
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Stack(
                                children: [
                                  if (_videoCoverUrl != null)
                                    Image.network(_videoCoverUrl!,
                                        fit: BoxFit.cover,
                                        width: double.infinity,
                                        height: double.infinity),
                                  const Center(
                                    child: Icon(Icons.play_circle_filled,
                                        size: 48, color: Colors.white),
                                  ),
                                  Positioned(
                                    top: 8,
                                    right: 8,
                                    child: GestureDetector(
                                      onTap: () => setState(() {
                                        _videoUrl = null;
                                        _videoCoverUrl = null;
                                      }),
                                      child: Container(
                                        padding: const EdgeInsets.all(4),
                                        decoration: const BoxDecoration(
                                            color: Colors.black54,
                                            shape: BoxShape.circle),
                                        child: const Icon(Icons.close,
                                            color: Colors.white, size: 16),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.video_library,
                                    size: 32, color: Colors.grey[400]),
                                const SizedBox(height: 8),
                                Text('点击选择视频文件',
                                    style: TextStyle(
                                        color: Colors.grey[600], fontSize: 14)),
                                const SizedBox(height: 4),
                                Text('支持MP4格式',
                                    style: TextStyle(
                                        color: Colors.grey[500], fontSize: 12)),
                              ],
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 商品内容区域
  Widget _buildServiceContentSection() {
    return Column(
      children: [
        // 封面图 - 移到最上面，使用卡片样式
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.photo, color: Colors.blue[600], size: 20),
                      const SizedBox(width: 8),
                      Text('封面图',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                    ],
                  ),
                  const SizedBox(height: 12),
                  GestureDetector(
                    onTap: _selectCoverImage,
                    child: Container(
                      width: double.infinity,
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(8),
                        border:
                            Border.all(color: Colors.grey[300]!, width: 1.5),
                      ),
                      child: _coverImageUrl != null
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Image.network(_coverImageUrl!,
                                  fit: BoxFit.cover,
                                  width: double.infinity,
                                  height: double.infinity),
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.add_photo_alternate,
                                    size: 48, color: Colors.grey[400]),
                                const SizedBox(height: 12),
                                Text('点击选择封面图',
                                    style: TextStyle(
                                        color: Colors.grey[600], fontSize: 14)),
                                const SizedBox(height: 4),
                                Text('建议尺寸：16:9',
                                    style: TextStyle(
                                        color: Colors.grey[500], fontSize: 12)),
                              ],
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        // 商品信息 - 优化布局
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.shopping_bag,
                          color: Colors.green[600], size: 20),
                      const SizedBox(width: 8),
                      Text('商品信息',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                    ],
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _productNameController,
                    decoration: InputDecoration(
                      labelText: '商品名称',
                      hintText: '请输入商品名称',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide:
                            BorderSide(color: Colors.blue[400]!, width: 2),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 16),
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _productPriceController,
                    decoration: InputDecoration(
                      labelText: '价格（元）',
                      hintText: '请输入价格',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide:
                            BorderSide(color: Colors.blue[400]!, width: 2),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 16),
                    ),
                    keyboardType: TextInputType.number,
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        // 商品图片
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.image, color: Colors.orange[600], size: 20),
                      const SizedBox(width: 8),
                      Text('商品图片',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                    ],
                  ),
                  const SizedBox(height: 12),
                  GestureDetector(
                    onTap: _selectProductImages,
                    child: Container(
                      width: double.infinity,
                      height: 120,
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(8),
                        border:
                            Border.all(color: Colors.grey[300]!, width: 1.5),
                      ),
                      child: _productImages.isNotEmpty
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Image.network(_productImages.first,
                                  fit: BoxFit.cover,
                                  width: double.infinity,
                                  height: double.infinity),
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.add_photo_alternate,
                                    size: 32, color: Colors.grey[400]),
                                const SizedBox(height: 8),
                                Text('点击选择商品图片',
                                    style: TextStyle(
                                        color: Colors.grey[600], fontSize: 14)),
                                const SizedBox(height: 4),
                                Text('可上传多张图片',
                                    style: TextStyle(
                                        color: Colors.grey[500], fontSize: 12)),
                              ],
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        // 商品描述
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: Card(
            elevation: 2,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.edit, color: Colors.purple[600], size: 20),
                      const SizedBox(width: 8),
                      Text('商品描述',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800])),
                    ],
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _productDescriptionController,
                    decoration: InputDecoration(
                      hintText: '详细描述你的商品特点、用途、优势等...',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey[300]!),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide:
                            BorderSide(color: Colors.blue[400]!, width: 2),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 16),
                    ),
                    maxLines: 4,
                    maxLength: 300,
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 20),
      ],
    );
  }

  /// 构建卡片容器
  Widget _buildCard(
      {required IconData icon, required String title, required Widget child}) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 3,
              offset: const Offset(0, 1))
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: Colors.blue[600], size: 20),
              const SizedBox(width: 8),
              Text(title,
                  style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87)),
            ],
          ),
          const SizedBox(height: 12),
          child,
        ],
      ),
    );
  }

  /// 选择封面图片
  void _selectCoverImage() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择图片',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                    child: _buildImageSourceOption(Icons.photo_library, '相册选择',
                        () {
                  Navigator.pop(context);
                  _pickImageFromGallery();
                })),
                const SizedBox(width: 16),
                Expanded(
                    child: _buildImageSourceOption(Icons.camera_alt, '拍照', () {
                  Navigator.pop(context);
                  _takePhoto();
                })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建图片选择选项
  Widget _buildImageSourceOption(
      IconData icon, String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.grey[50],
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey[200]!)),
        child: Column(children: [
          Icon(icon, size: 32, color: Colors.blue[600]),
          const SizedBox(height: 8),
          Text(title,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500))
        ]),
      ),
    );
  }

  /// 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    try {
      final picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) await _uploadCoverImage(File(image.path));
    } catch (e) {
      _showErrorSnackBar('选择图片失败: $e');
    }
  }

  /// 拍照
  Future<void> _takePhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) await _uploadCoverImage(File(photo.path));
    } catch (e) {
      _showErrorSnackBar('拍照失败: $e');
    }
  }

  /// 上传封面图片
  Future<void> _uploadCoverImage(File imageFile) async {
    try {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const AlertDialog(
                  content: Row(children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在压缩图片...')
              ])));
      
      // 先压缩图片
      final compressedFile = await CompressUtils.compressCoverImage(imageFile);
      if (compressedFile == null) {
        Navigator.pop(context);
        _showErrorSnackBar('图片压缩失败');
        return;
      }
      
      // 更新对话框提示
      Navigator.pop(context);
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const AlertDialog(
                  content: Row(children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在上传图片...')
              ])));
      
      final result = await ApiService().uploadPostImage(compressedFile);
      Navigator.pop(context);
      if (result['code'] == 200 || result['code'] == 0) {
        setState(() => _coverImageUrl = result['data']);
        _showSuccessSnackBar('图片上传成功');
      } else {
        _showErrorSnackBar(result['message'] ?? '图片上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      _showErrorSnackBar('图片上传失败: $e');
    }
  }

  /// 选择视频
  void _selectVideo() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择视频',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                    child: _buildImageSourceOption(Icons.video_library, '相册选择',
                        () {
                  Navigator.pop(context);
                  _pickVideoFromGallery();
                })),
                const SizedBox(width: 16),
                Expanded(
                    child: _buildImageSourceOption(Icons.videocam, '录制', () {
                  Navigator.pop(context);
                  _recordVideo();
                })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 选择视频封面
  void _selectVideoCover() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择视频封面',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                    child: _buildImageSourceOption(Icons.photo_library, '相册选择',
                        () {
                  Navigator.pop(context);
                  _pickVideoCoverFromGallery();
                })),
                const SizedBox(width: 16),
                Expanded(
                    child: _buildImageSourceOption(Icons.camera_alt, '拍照', () {
                  Navigator.pop(context);
                  _takeVideoCoverPhoto();
                })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 从相册选择视频封面
  Future<void> _pickVideoCoverFromGallery() async {
    try {
      final picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) await _uploadVideoCover(File(image.path));
    } catch (e) {
      Logger.e('PublishPostPageV4', '选择视频封面失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择视频封面失败: $e')),
      );
    }
  }

  /// 拍照作为视频封面
  Future<void> _takeVideoCoverPhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.camera);
      if (image != null) await _uploadVideoCover(File(image.path));
    } catch (e) {
      Logger.e('PublishPostPageV4', '拍照失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('拍照失败: $e')),
      );
    }
  }

  /// 上传视频封面
  Future<void> _uploadVideoCover(File imageFile) async {
    try {
      setState(() => _isLoading = true);
      
      // 先压缩图片
      final compressedFile = await CompressUtils.compressCoverImage(imageFile);
      if (compressedFile == null) {
        _showErrorSnackBar('图片压缩失败');
        return;
      }

      final result = await _apiService.uploadPostImage(compressedFile);
      if (result['code'] == 200 || result['code'] == 0) {
        setState(() => _videoCoverUrl = result['data']);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('视频封面上传成功')),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('视频封面上传失败: ${result['message'] ?? '未知错误'}')),
        );
      }
    } catch (e) {
      Logger.e('PublishPostPageV4', '上传视频封面失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                '上传视频封面失败: ${e is NetworkException ? e.message : e.toString()}')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  /// 从相册选择视频
  Future<void> _pickVideoFromGallery() async {
    try {
      // 先验证必填项
      if (!_validateVideoBeforeUpload()) {
        return;
      }

      final picker = ImagePicker();
      final XFile? video = await picker.pickVideo(source: ImageSource.gallery);
      if (video != null) await _uploadVideo(File(video.path));
    } catch (e) {
      _showErrorSnackBar('选择视频失败: $e');
    }
  }

  /// 录制视频
  Future<void> _recordVideo() async {
    try {
      // 先验证必填项
      if (!_validateVideoBeforeUpload()) {
        return;
      }

      final picker = ImagePicker();
      final XFile? video = await picker.pickVideo(source: ImageSource.camera);
      if (video != null) await _uploadVideo(File(video.path));
    } catch (e) {
      _showErrorSnackBar('录制视频失败: $e');
    }
  }

  /// 上传视频前验证必填项
  bool _validateVideoBeforeUpload() {
    // 验证视频描述
    if (_videoDescriptionController.text.trim().isEmpty) {
      _showErrorSnackBar('请先填写视频描述');
      return false;
    }

    // 验证视频封面
    if (_videoCoverUrl == null || _videoCoverUrl!.isEmpty) {
      _showErrorSnackBar('请先上传视频封面');
      return false;
    }

    return true;
  }

  /// 上传视频
  Future<void> _uploadVideo(File videoFile) async {
    try {
      // 再次验证（防止绕过验证）
      if (!_validateVideoBeforeUpload()) {
        return;
      }

      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const AlertDialog(
                  content: Row(children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在压缩视频...')
              ])));

      // 先压缩视频
      final compressedFile = await CompressUtils.compressVideo(videoFile);
      if (compressedFile == null) {
      Navigator.pop(context);
        _showErrorSnackBar('视频压缩失败');
        return;
      }

      // 更新对话框提示
      Navigator.pop(context);
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const AlertDialog(
                  content: Row(children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在上传视频...')
              ])));

      final result = await ApiService().uploadVideo(compressedFile);
      Navigator.pop(context);

      if (result['code'] == 200 || result['code'] == 0) {
        setState(() {
          _videoUrl = result['data'];
          // 如果后端返回了封面URL，使用后端的；否则使用已上传的封面
          if (result['coverUrl'] != null &&
              result['coverUrl'].toString().isNotEmpty) {
            _videoCoverUrl = result['coverUrl'];
          }
          // 如果还没有封面，记录警告（封面应该在视频上传前就上传好）
          if (_videoCoverUrl == null || _videoCoverUrl!.isEmpty) {
            Logger.w('PublishPostPageV4', '视频上传成功但封面为空，这不应该发生');
          }
        });
        _showSuccessSnackBar('视频上传成功');
      } else {
        _showErrorSnackBar(result['message'] ?? '视频上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      Logger.e('PublishPostPageV4', '视频上传失败: $e');
      _showErrorSnackBar(
          '视频上传失败: ${e is NetworkException ? e.message : e.toString()}');
    }
  }

  /// 选择商品图片
  void _selectProductImages() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择商品图片',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                    child: _buildImageSourceOption(Icons.photo_library, '相册选择',
                        () {
                  Navigator.pop(context);
                  _pickProductImagesFromGallery();
                })),
                const SizedBox(width: 16),
                Expanded(
                    child: _buildImageSourceOption(Icons.camera_alt, '拍照', () {
                  Navigator.pop(context);
                  _takeProductPhoto();
                })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 从相册选择商品图片
  Future<void> _pickProductImagesFromGallery() async {
    try {
      final picker = ImagePicker();
      final List<XFile> images = await picker.pickMultiImage();
      if (images.isNotEmpty)
        await _uploadProductImages(images.map((e) => File(e.path)).toList());
    } catch (e) {
      _showErrorSnackBar('选择图片失败: $e');
    }
  }

  /// 拍摄商品照片
  Future<void> _takeProductPhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) await _uploadProductImages([File(photo.path)]);
    } catch (e) {
      _showErrorSnackBar('拍照失败: $e');
    }
  }

  /// 上传商品图片
  Future<void> _uploadProductImages(List<File> imageFiles) async {
    try {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const AlertDialog(
                  content: Row(children: [
                CircularProgressIndicator(),
                SizedBox(width: 20),
                Text('正在压缩图片...')
              ])));
      
      // 先压缩所有图片
      List<File> compressedFiles = [];
      for (File imageFile in imageFiles) {
        final compressedFile = await CompressUtils.compressContentImage(imageFile);
        if (compressedFile != null) {
          compressedFiles.add(compressedFile);
        }
      }

      if (compressedFiles.isEmpty) {
        Navigator.pop(context);
        _showErrorSnackBar('图片压缩失败');
        return;
      }

      // 更新对话框提示
      Navigator.pop(context);
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const CircularProgressIndicator(),
                      const SizedBox(height: 20),
                      Text('正在上传图片 (${compressedFiles.length}张)...')
                    ],
                  )));

      List<String> uploadedUrls = [];
      for (int i = 0; i < compressedFiles.length; i++) {
        final result = await ApiService().uploadPostImage(compressedFiles[i]);
        if (result['code'] == 200 || result['code'] == 0) {
          uploadedUrls.add(result['data']);
        }
      }
      
      Navigator.pop(context);
      if (uploadedUrls.isNotEmpty) {
        setState(() => _productImages = uploadedUrls);
        _showSuccessSnackBar('图片上传成功');
      } else {
        _showErrorSnackBar('图片上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      _showErrorSnackBar('图片上传失败: $e');
    }
  }

  /// 加载分类
  Future<void> _loadCategories() async {
    try {
      final categoriesData = await ApiService().getContentCategories();
      setState(() {
        _categories = categoriesData
            .map((categoryJson) => Category.fromJson(categoryJson))
            .toList();
        if (_categories.isNotEmpty) _selectedCategory = _categories.first;
      });
      Logger.d('PublishPostPageV4', '成功加载分类: ${_categories.length}个');
    } catch (e) {
      Logger.e('PublishPostPageV4', '加载分类失败: $e');
      // 使用默认分类作为后备方案
      setState(() {
        _categories = [
          Category(id: '1', name: '科技'),
          Category(id: '2', name: '文娱'),
          Category(id: '3', name: '游戏'),
          Category(id: '4', name: '旅行'),
          Category(id: '5', name: '美食'),
          Category(id: '6', name: '运动'),
          Category(id: '7', name: '教育'),
          Category(id: '8', name: '其他'),
        ];
        _selectedCategory = _categories.first;
      });
    }
  }

  /// 发布动态
  Future<void> _publishPost() async {
    if (!_validateForm()) return;
    
    setState(() => _isPublishing = true);
    
    try {
      Map<String, dynamic> publishData = _buildPublishData();
      await ApiService().publishPost(publishData);
      _showSuccessSnackBar('发布成功！');
      Navigator.pop(context);
    } catch (e) {
      _showErrorSnackBar('发布失败: ${e is NetworkException ? e.message : '网络错误'}');
    } finally {
      setState(() => _isPublishing = false);
    }
  }

  /// 构建发布数据
  Map<String, dynamic> _buildPublishData() {
    Map<String, dynamic> data = {
      'postType': _selectedPostType,
      'title': _titleController.text.trim(),
      'categoryId': _selectedCategory!.id,
      'categoryName': _selectedCategory!.name,
      'visibility': 'public',
      'isOriginal': _isOriginal,
    };

    switch (_selectedPostType) {
      case 'article':
        data.addAll({
          'content': _articleContentController.content,
          'coverUrl': _coverImageUrl,
        });
        break;
      case 'video':
        data.addAll({
          'content': _videoDescriptionController.text.trim(),
          'videoUrl': _videoUrl,
          'coverUrl': _videoCoverUrl,
        });
        break;
      case 'service':
        data.addAll({
          'content': _productDescriptionController.text.trim(),
          'productName': _productNameController.text.trim(),
          'productPrice':
              double.tryParse(_productPriceController.text.trim()) ?? 0.0,
          'productImages': _productImages,
          'coverUrl': _coverImageUrl, // 添加封面图URL
        });
        break;
    }

    return data;
  }

  /// 验证表单
  bool _validateForm() {
    if (_titleController.text.trim().isEmpty) {
      _showErrorSnackBar('请输入标题');
      return false;
    }
    if (_titleController.text.trim().length < 2) {
      _showErrorSnackBar('标题至少需要2个字符');
      return false;
    }
    if (_selectedCategory == null) {
      _showErrorSnackBar('请选择分类');
      return false;
    }

    switch (_selectedPostType) {
      case 'article':
        if (_articleContentController.content.trim().isEmpty) {
          _showErrorSnackBar('请输入文章内容');
          return false;
        }
        break;
      case 'video':
        if (_videoUrl == null) {
          _showErrorSnackBar('请选择视频文件');
          return false;
        }
        if (_videoDescriptionController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入视频描述');
          return false;
        }
        break;
      case 'service':
        if (_productNameController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入商品名称');
          return false;
        }
        if (_productPriceController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入商品价格');
          return false;
        }
        if (_productImages.isEmpty) {
          _showErrorSnackBar('请选择商品图片');
          return false;
        }
        break;
    }

    return true;
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _articleContentController.dispose();
    _videoDescriptionController.dispose();
    _productNameController.dispose();
    _productPriceController.dispose();
    _productDescriptionController.dispose();
    super.dispose();
  }
}
